<template>
  <div>
    <el-form label-width="120px" :rules="formRules" :model="form" ref="formRef">
      <el-form-item label="部门名称" prop="name">
        <el-input
          style="width: 80%"
          placeholder="1-50个字符"
          v-model="form.name"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          style="width: 80%"
          placeholder="1-50个字符"
          v-model="form.code"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          value=""
          style="width: 30%"
          placeholder="请选择"
          v-model="form.manager"
        >
          <el-option
            v-for="item in simpleList"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
          v-model="form.introduce"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="small"
          @click.native="doSubmit(addDeptPid)"
          >确定</el-button
        >
        <el-button size="small" @click="doClose">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getSimpleEmployee,
  addDepartments,
  getDepartmentById,
  editDepartments,
} from "@/api/departments";

export default {
  props: {
    addDeptPid: {
      required: true,
      type: String,
    },
    isEdit: {
      type: Boolean,
      required: true,
    },
    originList: {
      type: Array,
      required: true,
    },
  },
  data() {
    const validateCode = (rules, value, callback) => {
      let codeList = this.originList.map((item) => item.code);
      if (this.isEdit) {
        codeList = this.originList
          .filter((item) => item.id !== this.addDeptPid)
          .map((item) => item.code);
      }
      codeList.includes(value)
        ? callback(new Error(`编码${value}已被占用`))
        : callback();
    };
    const validateName = (rules, value, callback) => {
      let nameList = this.originList
        .filter((item) => item.pid === this.addDeptPid)
        .map((item) => item.name);
      if (this.isEdit) {
        const index = this.originList.findIndex(
          (item) => item.id === this.addDeptPid
        );
        // console.log(index);
        const pid = this.originList[index].pid;
        // console.log(pid);
        nameList = this.originList
          .filter((item) => item.pid === pid && item.id !== this.addDeptPid)
          .map((item) => item.name);
      }
      console.log(nameList);
      nameList.includes(value)
        ? callback(new Error(`部门名字 ${value} 已被占用`))
        : callback();
    };
    return {
      form: {
        name: "", // 部门名称
        code: "", // 部门编码
        manager: "", // 部门管理者
        introduce: "", // 部门介绍
        pid: "", // 父级部门ID
      },
      simpleList: [],
      formRules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门名称要求1-50个字符",
            trigger: "blur",
          },
          {
            validator: validateName,
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门编码要求1-50个字符",
            trigger: "blur",
          },
          {
            validator: validateCode,
            trigger: "blur",
          },
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "change" },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          {
            min: 1,
            max: 300,
            message: "部门介绍要求1-300个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.loadSimpleEmployee();
    // this.loadDepartmentById(this.addDeptPid);
  },
  // watch: {
  //   addDeptPid: {
  //     handler(newValue, oldValue) {
  //       this.loadDepartmentById(this.addDeptPid);
  //     },
  //     immediate: true,
  //   },
  // },
  methods: {
    async loadDepartmentById(id) {
      if (this.isEdit) {
        const res = await getDepartmentById(id);
        console.log(res);
        this.form = { ...res.data };
      }
    },
    async loadSimpleEmployee() {
      const res = await getSimpleEmployee();
      //   console.log(res.data);
      this.simpleList = [...res.data];
    },
    async doSubmit(addDeptPid) {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd(addDeptPid);
        }
      });
      // if (this.isEdit) {
      //   // 编辑
      //   this.doEdit();
      // } else {
      //   // 新增
      //   this.doAdd(addDeptPid);
      // }
    },
    async doAdd(id) {
      this.form.pid = id;
      //   console.log(this.form);
      try {
        const res = await addDepartments(this.form);
        // console.log(res);
        this.$message.success(res.message);
        this.$emit("doSuccess");
      } catch (err) {
        console.dir(err);
        this.$message.error(err.message);
      }
    },
    async doEdit() {
      try {
        const res = await editDepartments(this.form);
        console.log(res);
        this.$message.success(res.message);
        this.$emit("doSuccess");
      } catch (err) {
        console.dir(err);
        this.$message.error(err.message);
      }
    },
    doClose() {
      this.$refs.formRef.resetFields();
      this.$emit("doClose");
    },
  },
};
</script>
